import sys
from threading import Thread
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
import json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "老年人综合保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 保障时间
                "days": ["1y"],
                # 保障数量
                "people_count": ["1", "2", "3", "4", "5"],
                # 意外伤残/身故
                "accident_death": ["200000"],
                # 意外伤害医疗
                "accident_medical": ["10000"],
                # 意外伤害住院津贴
                "accident_hospital": ["100/天"],
                # 航空保险
                "airplane_death": [""],
                # 火车保险
                "train_death": [""],
                # 汽车保险
                "passenger_death": [""],
                # 燃气保险
                "gas_death": [""],
                # 特色医疗服务
                "speMedicalSer": ["1"],
                # 产品计划
                "plan": ["全面款"]
            },
            "planB": {
                # 保障时间
                "days": ["1y"],
                # 保障数量
                "people_count": ["1", "2", "3", "4", "5"],
                # 意外伤残/身故
                "accident_death": ["100000"],
                # 意外伤害医疗
                "accident_medical": ["5000"],
                # 意外伤害住院津贴
                "accident_hospital": ["100/天"],
                # 航空保险
                "airplane_death": [""],
                # 火车保险
                "train_death": [""],
                # 汽车保险
                "passenger_death": [""],
                # 燃气保险
                "gas_death": [""],
                # 特色医疗服务
                "speMedicalSer": ["1"],
                # 产品计划
                "plan": ["热销款"]
            },
            "planC": {
                # 保障时间
                "days": ["1y"],
                # 保障数量
                "people_count": ["1", "2", "3", "4", "5"],
                # 意外伤残/身故
                "accident_death": ["50000", "100000", "150000", "200000"],
                # 意外伤害医疗
                "accident_medical": ["3000", "5000", "10000"],
                # 意外伤害住院津贴
                "accident_hospital": ["0", "50/天", "100/天"],
                # 航空保险
                "airplane_death": ["0", "500000", "1000000", "2000000"],
                # 火车保险
                "train_death": ["0", "500000", "800000", "1000000"],
                # 汽车保险
                "passenger_death": ["0", "100000", "200000", "300000"],
                # 燃气保险
                "gas_death": ["0", "50000"],
                # 特色医疗服务
                "speMedicalSer": ["1"],
                # 产品计划
                "plan": ["自定义"]
            }
        }

        for k in plan:
            for v in product(plan[k]["days"], plan[k]["people_count"], plan[k]["accident_death"],
                             plan[k]["accident_medical"], plan[k]["accident_hospital"], plan[k]["airplane_death"],
                             plan[k]["train_death"], plan[k]["passenger_death"], plan[k]["gas_death"],
                             plan[k]["speMedicalSer"], plan[k]["plan"]):
                data = Helper.formatProductInfo(plan[k], v)
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self, dt=None,mysql=None):

        if dt["plan"] == "全面款":
            data = {"planClass": 3, "amountFormList": [
                {"accidentalDeath": 200000, "suddenDeath": 0, "accidentalMedical": 10000, "gasDeath": 50000,
                 "fractures": 0, "hospitalizedAllowance": 100, "airplaneSuddennessDie": 0, "trainSuddennessDie": 0,
                 "carSuddennessDie": 0},
                {"accidentalDeath": 100000, "suddenDeath": 0, "accidentalMedical": 5000, "gasDeath": 0, "fractures": 0,
                 "hospitalizedAllowance": 100, "airplaneSuddennessDie": 0, "trainSuddennessDie": 0,
                 "carSuddennessDie": 0},
                {"accidentalDeath": 100000, "accidentalMedical": 10000, "airplaneSuddennessDie": 1000000,
                 "carSuddennessDie": 100000, "fractures": 0, "gasDeath": 50000, "hospitalizedAllowance": 50,
                 "trainSuddennessDie": 500000}], "insurantNumber": dt["people_count"], "beginDate": "2020-04-03"}
        elif dt["plan"] == "热销款":
            data = {"planClass": 4, "amountFormList": [
                {"accidentalDeath": 200000, "suddenDeath": 0, "accidentalMedical": 10000, "gasDeath": 50000,
                 "fractures": 0, "hospitalizedAllowance": 100, "airplaneSuddennessDie": 0, "trainSuddennessDie": 0,
                 "carSuddennessDie": 0},
                {"accidentalDeath": 100000, "suddenDeath": 0, "accidentalMedical": 5000, "gasDeath": 0, "fractures": 0,
                 "hospitalizedAllowance": 100, "airplaneSuddennessDie": 0, "trainSuddennessDie": 0,
                 "carSuddennessDie": 0},
                {"accidentalDeath": 100000, "accidentalMedical": 10000, "airplaneSuddennessDie": 1000000,
                 "carSuddennessDie": 100000, "fractures": 0, "gasDeath": 50000, "hospitalizedAllowance": 50,
                 "trainSuddennessDie": 500000}], "insurantNumber": dt["people_count"], "beginDate": "2020-04-03"}
        else:
            data = {"planClass": 5, "amountFormList": [
                {"accidentalDeath": 200000, "suddenDeath": 0, "accidentalMedical": 10000, "gasDeath": 50000, "fractures": 0,
                 "hospitalizedAllowance": 100, "airplaneSuddennessDie": 0, "trainSuddennessDie": 0, "carSuddennessDie": 0},
                {"accidentalDeath": 100000, "suddenDeath": 0, "accidentalMedical": 5000, "gasDeath": 0, "fractures": 0,
                 "hospitalizedAllowance": 100, "airplaneSuddennessDie": 0, "trainSuddennessDie": 0, "carSuddennessDie": 0},
                {"accidentalDeath": dt["accident_death"], "accidentalMedical": dt["accident_medical"], "airplaneSuddennessDie": dt["airplane_death"],
                 "carSuddennessDie": dt["passenger_death"], "fractures": 0, "gasDeath": dt["gas_death"], "hospitalizedAllowance": dt["accident_hospital"].replace("/天",""),
                 "trainSuddennessDie": dt["train_death"]}], "insurantNumber": dt["people_count"], "beginDate": "2020-04-03"}
        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200:
            if dt["plan"] == "全面款":
                price = r.json()["quoteResult1"]["toaUserPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
            elif dt["plan"] == "热销款":
                price = r.json()["quoteResult2"]["toaUserPremium"]

                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
            else:
                price = r.json()["quoteResult3"]["toaUserPremium"]
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
            mysql.updatePrice(data)
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])


    def main(self, mysql):
        while True:
            # 随机领取一条数据
            dt = mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)
            self.requestJson(dt, mysql)

    # 多线程
    def startProcess(self):
        for i in range(10):
            mysql = MysqlClient()
            t = Thread(target=self.main, args=(mysql,))
            t.start()

